package com.ruoyi.system.service.impl.fxImpl;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.fx.FxGoodModel;
import com.ruoyi.system.domain.fx.FxGoodclassify;
import com.ruoyi.system.domain.vo.FxGoodModelMtVo;
import com.ruoyi.system.domain.vo.FxGoodModelVo;
import com.ruoyi.system.mapper.fx.FxGoodModelMapper;
import com.ruoyi.system.mapper.fx.FxGoodclassifyMapper;
import com.ruoyi.system.service.fx.IFxGoodModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 商品模板Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-14
 */
@Service
public class FxGoodModelServiceImpl implements IFxGoodModelService
{
    @Autowired
    private FxGoodModelMapper fxGoodModelMapper;
    @Autowired
    private FxGoodclassifyMapper fxGoodclassifyMapper;


    /**
     * 查询商品模板
     *
     * @param id 商品模板主键
     * @return 商品模板
     */
    @Override
    public FxGoodModel selectFxGoodModelById(Long id)
    {
        return Optional.ofNullable(fxGoodModelMapper.selectFxGoodModelById(id))
                .map(model -> {
                    if (StringUtils.isNotEmpty(model.getSpecifications())) {
                        model.setSpecificationsList(Arrays.asList(model.getSpecifications().split(";")));
                    }
                    return model;
                }).orElse(null);
    }

    /**
     * 查询商品模板列表
     *
     * @param fxGoodModel 商品模板
     * @return 商品模板
     */
    @Override
    public List<FxGoodModel> selectFxGoodModelList(FxGoodModel fxGoodModel)
    {
        List<FxGoodModel> modelList = fxGoodModelMapper.selectFxGoodModelList(fxGoodModel);
        if (StringUtils.isEmpty(modelList)) {
            return new ArrayList<>();
        }
        modelList.forEach(model -> {
            if (StringUtils.isNotEmpty(model.getSpecifications())) {
                model.setSpecificationsList(Arrays.asList(model.getSpecifications().split(";")));
            }
        });
        return modelList;
    }

    @Override
    public List<FxGoodModel> selectFxGoodModelSonList(FxGoodModel fxGoodModel) {
        return fxGoodModelMapper.selectFxGoodModelSonList(fxGoodModel);
    }

    /**
     * 新增商品模板
     *
     * @param fxGoodModel 商品模板
     * @return 结果
     */
    @Override
    public int saveGoodModel(FxGoodModel fxGoodModel)
    {
        List<FxGoodModel> goodModel = fxGoodModelMapper.selectFxGoodModelClassifyId(fxGoodModel.getGoodName(),fxGoodModel.getId(),fxGoodModel.getParentId());
        // 判断是否具有id 有id则为修改
        if (!ObjectUtils.isEmpty(fxGoodModel.getId())){

            if (!CollectionUtils.isEmpty(goodModel)){
                throw new GlobalException("“ " + fxGoodModel.getGoodName() + " ”，当前模板名称已存在");
            }
            fxGoodModel.setCreateTime(DateUtils.getNowDate());
            return fxGoodModelMapper.updateFxGoodModel(fxGoodModel);
        }
        if (!CollectionUtils.isEmpty(goodModel)) {
            throw new GlobalException("“ " + fxGoodModel.getGoodName() + " ”，当前模板名称已存在，请勿再次添加");
        }
        return fxGoodModelMapper.insertFxGoodModel(fxGoodModel);
    }


    /**
     * 批量删除商品模板
     *
     * @param ids 需要删除的商品模板主键
     * @return 结果
     */
    @Override
    public int deleteFxGoodModelByIds(Long[] ids)
    {
        return fxGoodModelMapper.deleteFxGoodModelByIds(ids);
    }

    /**
     * 批量删除
     * @param classifyIds （第三级目录id）
     * @return
     */
    @Override
    public int deleteFxGoodModelByClassifyIds(Long[] classifyIds)
    {
        return fxGoodModelMapper.deleteFxGoodModelByClassifyIds(classifyIds);
    }

    /**
     * 删除商品模板信息
     *
     * @param id 商品模板主键
     * @return 结果
     */
    @Override
    public int deleteFxGoodModelById(Long id)
    {
        return fxGoodModelMapper.deleteFxGoodModelById(id);
    }

    @Override
    public FxGoodModelVo queryHierarchy(int hierarchy) {

        FxGoodModelVo vo = new FxGoodModelVo();
        FxGoodclassify fxGoodclassify = fxGoodclassifyMapper.selectFxGoodclassifyById((long) hierarchy);
        if (StringUtils.isNotNull(fxGoodclassify)) {
            vo.setGoodName(fxGoodclassify.getDeptName()+ "**");
            vo.setGoodImg(fxGoodclassify.getClassifyImg());
        }
        List<FxGoodModel> modelList = Optional.ofNullable(fxGoodModelMapper.selectFxGoodModel(hierarchy)).orElse(new ArrayList<>());


        Map<Long, List <FxGoodModel>> map = new HashMap<>();
        List<Map<String,List<String>>> mapnew =new ArrayList<>();
        for (FxGoodModel fxGoodModel : modelList) {
            if (StringUtils.isNotEmpty(fxGoodModel.getSpecifications())&&fxGoodModel.getSpecifications().indexOf("：")>0){
                Map<String, List<String>> maps = new HashMap<>();
                String specifications = fxGoodModel.getSpecifications();
                String[] split = specifications.split("。");
                for (String s : split) {
                    String substring = s.substring(0, s.indexOf("："));
                    List<String> strings = Arrays.asList(s.substring(s.indexOf("：") + 1).split("，"));
                    maps.put(substring,strings);
                }
                mapnew.add(maps);
                fxGoodModel.setMap(mapnew);
            }

            if (!fxGoodModel.getParentId().equals(0L)&& map.containsKey(fxGoodModel.getParentId())){
                map.get(fxGoodModel.getParentId()).add(fxGoodModel);
            }else {
                List<FxGoodModel> fxGoodModels = new ArrayList<>();
                fxGoodModels.add(fxGoodModel);
                map.put(fxGoodModel.getParentId(),fxGoodModels);
            }
        }

        List<FxGoodModel> collect = modelList.stream().filter(item -> ObjectUtils.isEmpty(item.getParentId()) || item.getParentId().equals(0L)).collect(Collectors.toList());

        collect.forEach(model -> {
            if (map.containsKey(model.getId())){
                model.setGoodModelList( map.get(model.getId()));
            }

//            if (StringUtils.isNotEmpty(model.getSpecifications())) {
//                model.setSpecificationsList(Arrays.asList(model.getSpecifications().split(";")));
//            }
        });
        vo.setModelList(collect);
        return vo;
    }

    /**
     * 查询模板信息 （会返回id值）
     * @param tierVal
     * @return
     */
    @Override
    public FxGoodModel queryModel(Integer tierVal) {
        return Optional.ofNullable(fxGoodModelMapper.selectFxGoodModelByClassifyId(tierVal)).orElse(new FxGoodModel());
    }

    /**
     * 查询模板名称
     * @param tierVal id
     * @return
     */
    @Override
    public FxGoodModelVo queryModelName(Long tierVal) {
        FxGoodModelVo vo = new FxGoodModelVo();
        FxGoodclassify fxGoodclassify = fxGoodclassifyMapper.selectFxGoodclassifyById(tierVal);
        if (StringUtils.isNotNull(fxGoodclassify)) {
            vo.setGoodName(fxGoodclassify.getDeptName()+ "**");
            vo.setGoodImg(fxGoodclassify.getClassifyImg());
        }
        List<FxGoodModel> modelList = Optional.ofNullable(fxGoodModelMapper.selectGoodModelIdList(tierVal)).orElse(new ArrayList<>());
        modelList.forEach(model -> {
            if (StringUtils.isNotEmpty(model.getSpecifications())) {
                model.setSpecificationsList(Arrays.asList(model.getSpecifications().split(";")));
            }
        });
        vo.setModelList(modelList);
        return vo;
    }

    /**
     * 导出美团商品模板列表
     */
    @Override
    public List<FxGoodModelMtVo> selectExport(FxGoodModel fxGoodModel) {
        return fxGoodModelMapper.selectExport(fxGoodModel);
    }


    /**
     * 批量新增模板
     */
    public int saveBath(List<FxGoodModel> fxGoodModels) {

        return fxGoodModelMapper.saveBath(fxGoodModels);
    }

    @Override
    @Transactional
    public void importMb(MultipartFile file, HttpServletResponse response) {
        ExcelUtil<FxGoodModelMtVo> util = new ExcelUtil<FxGoodModelMtVo>(FxGoodModelMtVo.class);
        try {
            List<FxGoodModelMtVo> fxGoodModelMtVos = util.importExcel(file.getInputStream());

            //父模板
            Map<String, FxGoodModel> map = new HashMap<>();
            //子模板
            Map<String, List<FxGoodModel>> mapSon = new HashMap<>();
            for (FxGoodModelMtVo fxGoodModelMtVo : fxGoodModelMtVos) {
                // 父模板装一个map
                if (!map.containsKey(fxGoodModelMtVo.getGoodName())){
                    fxGoodModelMtVo.setParentId(0L);
                    map.put(fxGoodModelMtVo.getGoodName(), BeanUtil.copyProperties(fxGoodModelMtVo, FxGoodModel.class));
                    //子模板装另一个map
                }else{
                    if (mapSon.containsKey(fxGoodModelMtVo.getGoodName())){
                        FxGoodModel fxGoodModel = BeanUtil.copyProperties(fxGoodModelMtVo, FxGoodModel.class);
                        fxGoodModel.setGoodName(fxGoodModelMtVo.getSonGoodName());
                        mapSon.get(fxGoodModelMtVo.getGoodName()).add(fxGoodModel);
                    }else {
                        List<FxGoodModel> list = new ArrayList<>();
                        FxGoodModel fxGoodModel = BeanUtil.copyProperties(fxGoodModelMtVo, FxGoodModel.class);
                        fxGoodModel.setGoodName(fxGoodModelMtVo.getSonGoodName());
                        list.add(fxGoodModel);
                        mapSon.put(fxGoodModelMtVo.getGoodName(),list);
                    }
                }
            }
            //批量新增父模板获取自增长id
            List<FxGoodModel> fxGoodModels = new ArrayList<>(map.values());
            if (!CollectionUtils.isEmpty(fxGoodModels)){
                this.saveBath(fxGoodModels);
            }
            //遍历子模板填充父id
            List<FxGoodModel> sonFxGoodModel = new ArrayList<>();
            mapSon.forEach((k,v)->{
                FxGoodModel fxGoodModel = map.get(k);
                for (FxGoodModel goodModel : v) {
                    goodModel.setParentId(fxGoodModel.getId());
                }
                sonFxGoodModel.addAll(v);
            });
            //批量新增子模板
            if (!CollectionUtils.isEmpty(sonFxGoodModel)){
                this.saveBath(sonFxGoodModel);
            }
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(JSON.toJSONString(AjaxResult.success("导入成功")));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("导入异常请联系管理员");
        }
    }
}
